package com.hotau;

import java.util.Stack;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hotau.account.AccountManageFragment;
import com.hotau.framework.FooterVisible;
import com.hotau.framework.HeaderNotVisible;
import com.hotau.framework.IndexFragment;
import com.hotau.framework.LeftBtnVisible;
import com.hotau.framework.LoginNotVisible;
import com.hotau.framework.NOReturnable;
import com.hotau.framework.NeedAllowIncome;
import com.hotau.framework.NeedAllowOutlay;
import com.hotau.framework.NeedLogin;
import com.hotau.framework.RightBtnVisible;
import com.hotau.framework.SearchBarVisible;
import com.hotau.geo.GeoMapFragment;
import com.hotau.location.InstructionFragment;
import com.hotau.location.LoadingFragment;
import com.hotau.location.TogetherFragment;
import com.hotau.member.LoginFragment;
import com.hotau.member.service.MemberService;
import com.hotau.product.ProductListFragment;
import com.hotau.product.category.ProductCategoryFragment;
import com.hotau.setting.SettingFragment;
import com.hotau.util.DialogUtil;
import com.hotau.util.HttpUtil;
import com.hotau.util.SaveLoginInfoUtil;

/**
 * @author CruiseDing</br> 2011-8-18 下午08:53:11
 */
public class NavigationActivity extends FragmentActivity {

	// private static final PayFragment fragment = null;
	public Button leftButton;
	public Button rightButton;
	public Button categoryButton;
	
	public TextView leftText;
	public EditText keywordText;
	public Stack<Fragment> fragmentStack = new Stack<Fragment>();
	protected Stack<String> titleStack = new Stack<String>();
	protected Button exitButton;
	protected ImageButton searchButton;
	
	public RelativeLayout navigation_bar;
	public RelativeLayout search_bar;
	public LinearLayout navigation_footer;
	
	public static int NAVBAR_HEIGHT = 45;
	public static int FOOTER_HEIGHT = 60;

	public static final int TITLE_LENGTH = 6;
	
	/**
	 * 加载fragment
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.navigation);
		
		navigation_bar = (RelativeLayout) findViewById(R.id.navigation_bar);
		navigation_footer = (LinearLayout) findViewById(R.id.navigation_footer);
		NAVBAR_HEIGHT = navigation_bar.getLayoutParams().height;
		FOOTER_HEIGHT = navigation_footer.getLayoutParams().height;
		
		search_bar = (RelativeLayout) findViewById(R.id.search_bar);
		keywordText = (EditText)findViewById(R.id.search_word_input);
		keywordText.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
						.hideSoftInputFromWindow(
								((NavigationActivity)v.getContext())
									.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
				
				if(keyCode == KeyEvent.KEYCODE_ENTER){//修改回车键功能
					NavigationActivity root = (NavigationActivity)v.getContext();
					if(!(root.fragmentStack.peek() instanceof ProductListFragment)) {
						
						String keywords = keywordText.getText().toString();
						
						Bundle searchBundle = new Bundle();
						searchBundle.putString("keyword", keywords);
						ProductListFragment fragment = new ProductListFragment();
						fragment.setArguments(searchBundle);
						root.pushFragment("", fragment);
					}
				}
				return false;
			}
		});
		
				
		categoryButton = (Button)findViewById(R.id.search_category_btn);
		categoryButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				NavigationActivity root = (NavigationActivity)v.getContext();
				root.pushFragment("", new ProductCategoryFragment());
			}
		});
		
		searchButton = (ImageButton)findViewById(R.id.search_main_button);
		searchButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				NavigationActivity root = (NavigationActivity)v.getContext();
				root.pushFragment("", new GeoMapFragment());
			}
		});
		
		leftText = (TextView) findViewById(R.id.navigation_txt_left);
		leftButton = (Button) findViewById(R.id.navigation_button_left);
		leftButton.setText("返回");
		leftButton.setBackgroundResource(R.drawable.nowhite);
		leftButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popFragment();
			}
		});

		exitButton = (Button) findViewById(R.id.framework_exist_btn);
		rightButton = exitButton;
		exitButton.setText("注销");

		if (MemberService.isLogin(this)) {
			exitButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.d("mytag", "点击注销。。。。。。");
					Dialog dialog = new AlertDialog.Builder(
							NavigationActivity.this)
							.setTitle("提示")
							.setMessage("确定注销?")
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											dialog.dismiss();
										}
									})
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											MemberService.logout(NavigationActivity.this);
											dialog.dismiss();
											toHome();
										}
									}).create();
					dialog.show();
				}
			});
		} else {

		}
		initTabs();
	}
	
	private View homeTab = null;
	private View acc_m_Tab = null;
	private View pay_m_Tab = null;
	private View order_m_Tab = null;
	private View more_Tab = null;

	public void initTabs() {

		// 初始化navigation_bar
		navigation_bar.setBackgroundResource(R.drawable.headerbanner);

		// home
		homeTab = findViewById(R.id.tab_home);
		homeTab.setBackgroundResource(R.drawable.tab_home_clicked);
		homeTab.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Fragment currentFragment = null;
				try {
					currentFragment = fragmentStack.peek();
				} catch (Exception e) {
					// do nothing
				}
				if (currentFragment != null
						&& currentFragment instanceof TogetherFragment) {
					return;
				}
				toHome();
			}
		});
		// 账户管理
		acc_m_Tab = findViewById(R.id.tab_acc_m);
		acc_m_Tab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!HttpUtil.hasInternet(NavigationActivity.this)) {
					DialogUtil.showDialog(NavigationActivity.this, "",
							getString(R.string.connection_fail));
					return;
				}

				Fragment currentFragment = null;
				try {
					currentFragment = fragmentStack.peek();
				} catch (Exception e) {
					// do nothing
				}

				if (currentFragment != null
						&& currentFragment instanceof AccountManageFragment) {
					return;
				}
				pushFragment("账户管理", new AccountManageFragment());
			}
		});

		// 支付管理
		pay_m_Tab = findViewById(R.id.tab_pay_m);
		pay_m_Tab.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!HttpUtil.hasInternet(NavigationActivity.this)) {
					DialogUtil.showDialog(NavigationActivity.this, "",
							getString(R.string.connection_fail));
					return;
				}

				Fragment currentFragment = null;
				try {
					currentFragment = fragmentStack.peek();
				} catch (Exception e) {
					// do nothing
				}
			}
		});

		// 订单管理
		order_m_Tab = findViewById(R.id.tab_order_m);
		order_m_Tab.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (!HttpUtil.hasInternet(NavigationActivity.this)) {
					DialogUtil.showDialog(NavigationActivity.this, "",
							getString(R.string.connection_fail));
					return;
				}

				Fragment currentFragment = null;
				try {
					currentFragment = fragmentStack.peek();
				} catch (Exception e) {
					// do nothing
				}
			}
		});

		// 更多
		more_Tab = findViewById(R.id.tab_more);
		more_Tab.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (!HttpUtil.hasInternet(NavigationActivity.this)) {
					DialogUtil.showDialog(NavigationActivity.this, "",
							getString(R.string.connection_fail));
					return;
				}

				// if (!MemberService.isActivate(NavigationActivity.this)) {
				// DialogUtil.showDialog(NavigationActivity.this, "",
				// "帐户未激活，请激活。");
				// return;
				// }

				Fragment currentFragment = null;
				try {
					currentFragment = fragmentStack.peek();
				} catch (Exception e) {
					// do nothing
				}

				if (currentFragment != null
						&& currentFragment instanceof SettingFragment) {
					return;
				}

				pushFragment("更多", new SettingFragment());
			}
		});

	}

	public void viewLogo(Fragment topFragment) {
		if (topFragment instanceof TogetherFragment
				&& MemberService.isLogin(NavigationActivity.this))
			leftText.setVisibility(View.VISIBLE);
		else
			leftText.setVisibility(View.GONE);
	}

	public void judgeTabsByFragment() {

		try {
			Fragment topFragment = fragmentStack.peek();
			Log.d("mytag", "开始判断。。。。");
			homeTab.setBackgroundResource(R.drawable.tab_home_default2);
			acc_m_Tab.setBackgroundResource(R.drawable.tab_accm_default2);
			pay_m_Tab.setBackgroundResource(R.drawable.tab_paym_default2);
			order_m_Tab.setBackgroundResource(R.drawable.tab_orderm_default2);
			more_Tab.setBackgroundResource(R.drawable.tab_more_default2);
			if (topFragment instanceof TogetherFragment) {
				homeTab.setBackgroundResource(R.drawable.tab_home_clicked);
			} else if (topFragment instanceof AccountManageFragment) {
				acc_m_Tab.setBackgroundResource(R.drawable.tab_accm_clicked);
			}
			// else if (topFragment instanceof PayMainFragment) {
			// pay_m_Tab.setBackgroundResource(R.drawable.tab_paym_clicked);
			// } else if (topFragment instanceof OrderManagementFragment) {
			// order_m_Tab.setBackgroundResource(R.drawable.tab_orderm_clicked);
			// }
			else if (topFragment instanceof SettingFragment) {
				more_Tab.setBackgroundResource(R.drawable.tab_more_clicked);
			}
			viewLogo(topFragment);
		} catch (Exception ex) {
			ex.printStackTrace();
			Log.e("mytag", "fragmentStack.peek()出错");
		}
	}

	public void toHome() {
		int size = fragmentStack.size();
		Log.i("mytag", "回首页fragmentStack size=" + size);

		if (fragmentStack.size() == 1
				&& fragmentStack.peek() instanceof TogetherFragment) {
			// 刷新首页
			footerVisible();
			searchVisible();
			leftBtnVisible();
			rightBtnVisible();
		}

		for (int i = size; i > 1; i--) {
			Log.i("mytag", "弹出fragmentStack...");
			Fragment fragment = fragmentStack.peek();
			if (fragment instanceof TogetherFragment) {
				// 刷新首页
				footerVisible();
				searchVisible();
				leftBtnVisible();
				rightBtnVisible();
				return;
			} else {
				popFragment();
			}
		}
	}

	public void toHomeAndPush(String title, Fragment fragment) {
		int size = fragmentStack.size();
		for (int i = size; i > 0; i--) {
			Fragment currentFragment = fragmentStack.peek();
			if (currentFragment instanceof TogetherFragment) {
				pushFragment(title, fragment);
				return;
			} else {
				popFragment();
			}
		}
	}

	/**
	 * 设置标题文本
	 * 
	 * @param title
	 */
	private void setTitle() {
		if (titleStack.size() != 0) {
			TextView titleView = (TextView) findViewById(R.id.navigation_title_text);
			String title = titleStack.peek();
			if ("".equals(title.trim())) {
				titleView.setVisibility(View.GONE);
			} else {
				titleView.setVisibility(View.VISIBLE);
			}
			if (title.length() > TITLE_LENGTH) {
				title = title.substring(0, TITLE_LENGTH) + "...";
			}
			titleView.setText(title);
		}

	}

	public void pushFragment(final String title, final Fragment fragment) {

		if (fragment instanceof NeedLogin && !MemberService.isLogin(NavigationActivity.this)) {
			DialogUtil.showDialog(NavigationActivity.this, "提示", "您还未登录，请登陆！",
					new Executable() {
						@Override
						public void execute() {
							HotauActivity activity = new HotauActivity();
							System.out.println(activity.isReceivedNotificationOrder());
							if (activity.isReceivedNotificationOrder()) {
								if (fragment instanceof IndexFragment) {
									int size = fragmentStack.size();
									System.out.println(size);
									for (int i = size; i > 1; i--) {
										Fragment currentFragment = fragmentStack.peek();
										if (currentFragment instanceof TogetherFragment) {
											break;
										} else {
											popFragment();
										}
									}
								}
							}
							
							Bundle loginBundle = new Bundle();
							loginBundle.putString("fragmentNeedLoginName", title);
							loginBundle.putBoolean("finishLogin", true);
							loginBundle.putSerializable("fragmentNeedLogin", (NeedLogin)fragment);
							Fragment loginFragment = new LoginFragment();
							loginFragment.setArguments(loginBundle);
							
							pushFragment("登录", loginFragment);
						}
					});

			return;
		}

		if (fragment instanceof NeedAllowIncome
				&& MemberService.isIncomeForbidden(NavigationActivity.this)) {
			DialogUtil.showDialog(NavigationActivity.this, "", "帐户状态为"
					+ MemberService.getAccStatusName(NavigationActivity.this)
					+ "，不能进行此操作。");
			return;
		}

		if (fragment instanceof NeedAllowOutlay
				&& MemberService.isOutlayForbidden(NavigationActivity.this)) {
			DialogUtil.showDialog(NavigationActivity.this, "", "帐户状态为"
					+ MemberService.getAccStatusName(NavigationActivity.this)
					+ "，不能进行此操作。");
			return;
		}

		if (fragment instanceof IndexFragment) {
			int size = fragmentStack.size();
			for (int i = size; i > 1; i--) {

				Fragment currentFragment = fragmentStack.peek();
				if (currentFragment instanceof TogetherFragment) {
					break;
				} else {
					popFragment();
				}
			}
		}

		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		if ((fragment instanceof InstructionFragment)
				|| (fragment instanceof LoadingFragment)) {
			ft.replace(R.id.navigation_container, fragment);
			ft.commit();
			navigation_footer.setVisibility(View.GONE);
			navigation_bar.setVisibility(View.GONE);
			search_bar.setVisibility(View.GONE);
			return;
		} else {
			hideSoftInput();
			fragmentStack.push(fragment);
			titleStack.push(title);
			setTitle();
			
			hiddenReturnButton();
			hiddenExitButton();
			leftBtnVisible();
			rightBtnVisible();
			
			footerVisible();
			ft.replace(R.id.navigation_container, fragment);
			if (fragmentStack.size() > 1) {
				ft.addToBackStack("HNAIR");
			}
			ft.commit();

			Log.d("mytag", "压入fragment=" + fragment + " size=" + fragmentStack.size());

			judgeTabsByFragment();
			navigationBarVisible();
			searchVisible();
			headerVisible();
		}
	}

	private void navigationBarVisible() {

		try {
			Fragment fragment = fragmentStack.peek();

			if (fragment instanceof HeaderNotVisible) {
				navigation_bar.setVisibility(View.GONE);
			} else {
				navigation_bar.setVisibility(View.VISIBLE);
				navigation_bar.setBackgroundResource(R.drawable.headerbg);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			Log.e("mytag", "fragmentStack.peek()出错");
		}

	}

	public void popFragements(int i) {

		for (int j = 0; j < i; j++) {
			popFragment();
		}
	}

	public Fragment currentFragment() {
		return fragmentStack.peek();
	}

	/**
	 * 弹出
	 */
	public void popFragment() {
		hideSoftInput();
		getSupportFragmentManager().popBackStackImmediate();
		Fragment fragment = fragmentStack.pop();

		getSupportFragmentManager().beginTransaction().remove(fragment)
				.commit();
		titleStack.pop();
		setTitle();
		hiddenReturnButton();
		hiddenExitButton();
		hideLoginNotVisible();
		
		leftBtnVisible();
		rightBtnVisible();
		
		footerVisible();
		Log.d("mytag", "弹出fragment=" + fragment + " size=" + fragmentStack.size());
		judgeTabsByFragment();
		navigationBarVisible();
		searchVisible();
		headerVisible();
	}

	private void headerVisible() {
		try {
			Fragment fragment = fragmentStack.peek();
			if (fragment instanceof HeaderNotVisible) {
				navigation_bar.setVisibility(View.GONE);
				search_bar.setVisibility(View.GONE);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			Log.e("mytag", "fragmentStack.peek()出错");
		}
		
	}

	private void hiddenExitButton() {
		if (!MemberService.isLogin(this)) {
			// exitButton.setBackgroundResource(R.drawable.navigation_login);
			exitButton.setText("登录");
		} else {
			// exitButton.setBackgroundResource(R.drawable.navigation_back);
			exitButton.setText("退出");
		}
	}

	public Button getRightButton() {
		return rightButton;
	}

	private void footerVisible() {
		try {
			Fragment fragment = fragmentStack.peek();
			if (fragment instanceof FooterVisible) {
				findViewById(R.id.navigation_footer)
						.setVisibility(View.VISIBLE);
			} else {
				findViewById(R.id.navigation_footer).setVisibility(View.GONE);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			Log.e("mytag", "fragmentStack.peek()出错");
		}

	}

	private void leftBtnVisible() {
		try {
			Log.d("mytag", "开始处理左上角按钮");
			Fragment fragment = fragmentStack.peek();
			if (fragment instanceof LeftBtnVisible) {
				LeftBtnVisible leftBtnVisible = LeftBtnVisible.class
						.cast(fragment);
				Button btn = (Button) findViewById(R.id.navigation_button_left);
				btn.setVisibility(View.VISIBLE);
				leftBtnVisible.processLeftBtn(NavigationActivity.this, btn);
			} else {
				leftButton.setText("返回");
				leftButton.setBackgroundResource(R.drawable.nowhite);
				leftButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						popFragment();
					}
				});
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			Log.e("mytag", "fragmentStack.peek()出错");
		}
	}
	
	private void rightBtnVisible() {
		try {
			Log.d("mytag", "开始处理右上角按钮");
			Fragment fragment = fragmentStack.peek();
			if (fragment instanceof RightBtnVisible) {
				RightBtnVisible rightBtnVisible = RightBtnVisible.class
						.cast(fragment);
				Button rightBtn = (Button) findViewById(R.id.framework_exist_btn);
				rightBtn.setVisibility(View.VISIBLE);
				rightBtnVisible.processRightBtn(NavigationActivity.this,
						rightBtn);
			} else {
				findViewById(R.id.framework_exist_btn).setVisibility(View.GONE);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			Log.e("mytag", "fragmentStack.peek()出错");
		}
	}

	private void searchVisible() {
		try {
			Fragment fragment = fragmentStack.peek();

			if (fragment instanceof SearchBarVisible) {
				navigation_bar.setVisibility(View.GONE);
				search_bar.setVisibility(View.VISIBLE);
			} else {
				navigation_bar.setVisibility(View.VISIBLE);
				search_bar.setVisibility(View.GONE);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			Log.e("mytag", "fragmentStack.peek()出错");
		}
	}

	private void hideLoginNotVisible() {
		try {
			Fragment fragment = fragmentStack.peek();
			if (fragment instanceof LoginNotVisible
					&& SaveLoginInfoUtil.isLogin(this)) {
				this.popFragment();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			Log.e("mytag", "fragmentStack.peek()出错");
		}
	}

	public void hiddenReturnButton() {
		try {
			Fragment fragment = fragmentStack.peek();
			if (fragment instanceof NOReturnable || fragmentStack.size() < 2) {
				leftButton.setVisibility(View.GONE);
			} else {
				leftButton.setVisibility(View.VISIBLE);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			Log.e("mytag", "fragmentStack.peek()出错");
		}

	}

	public void immediatelyHiddenReturnButton() {
		leftButton.setVisibility(View.GONE);
	}

	private void hideSoftInput() {
		// 隐藏软软键盘
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(leftButton.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {

		int count = this.getSupportFragmentManager().getBackStackEntryCount();
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			Log.d("mytag", "count = " + count);

			if (count < 1 || fragmentStack.peek() instanceof TogetherFragment) {

				Dialog dialog = new AlertDialog.Builder(this)
						.setTitle("提示")
						.setMessage("确定退出应用程序?")
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {

										dialog.dismiss();
									}
								})
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										MemberService
												.logout(NavigationActivity.this);
										dialog.dismiss();
										NavigationActivity.this.finish();

										// MemberService
										// .logout(NavigationActivity.this);
										// dialog.dismiss();
										// toHome();

									}
								}).create();
				dialog.show();

			} else {
				if (fragmentStack.peek() instanceof NOReturnable) {
					return false;
				}
				boolean isProcess = super.onKeyUp(keyCode, event);
				if (isProcess) {
					Fragment fragment = fragmentStack.pop();
					titleStack.pop();
					setTitle();
					hideSoftInput();
					hiddenReturnButton();
					hiddenExitButton();
					hideLoginNotVisible();
					footerVisible();
					searchVisible();
					leftBtnVisible();
					rightBtnVisible();
					Log.d("mytag", "弹出fragment=" + fragment + " size="
							+ fragmentStack.size());
					judgeTabsByFragment();
					navigationBarVisible();
					searchVisible();
					headerVisible();
				}
				return isProcess;
			}
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}
}
